use std::{collections::HashMap, convert::Infallible, sync::Arc};

use serde_json::json;
use tokio::sync::Mutex;

use crate::client::create_client;

pub async fn get_me_token_data(
    mint: String,
    db: Arc<Mutex<HashMap<String, serde_json::Value>>>,
) -> Result<warp::reply::WithHeader<warp::reply::WithHeader<warp::reply::Json>>, Infallible> {
    let url = format!(
        "	https://api-mainnet.magiceden.io/rpc/getNFTByMintAddressCached/{}?useRarity=true",
        mint
    );

    let data: serde_json::Value;

    let db = db.lock().await;

    if let Some(value) = db.get(&mint) {
        data = value.clone();
    } else {
        data = match create_client(None).unwrap().get(url).send().await {
            Ok(data) => match data.json().await {
                Ok(data) => data,
                Err(_) => json!({}),
            },
            Err(_) => json!({}),
        };
    }

    let reply = warp::reply::json(&data);

    Ok(warp::reply::with_header(
        warp::reply::with_header(reply, "Access-Control-Allow-Origin", "*"),
        "Access-Control-Allow-Headers",
        "*",
    ))
}
